<template>
  <a-modal
    :title='title'
    :width='1100'
    :visible='visible'
    :confirmLoading='confirmLoading'
    :maskClosable='false'
    :destroyOnClose='true'
    @ok='handleSubmit'
    @cancel='handleCancel'
  >
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <div style='margin-bottom: 20px' v-if="mode=='add'">
          <a-button style='margin-bottom: 10px' @click='addFwnrList'>增加一项</a-button>
          <table border='1' style='border-color: #e8e8e8;width: 100%;text-align: center'>
            <tr style='font-weight: 600'>
              <td>服务名称</td>
              <td>标准价格</td>
              <td>成交价格</td>
              <td>服务周期（月）</td>
              <td>本次收款</td>
              <td>剩余尾款</td>
              <td>操作</td>
            </tr>
            <tr v-for='(item,index) in fwnr'>
              <td style='min-width: 280px'>
                <a-select
                  allowClear
                  show-search
                  :filter-option='filterOption'
                  placeholder='请选择服务内容'
                  v-model='item.service_id'
                  @change='setTrData($event,index)'
                >
                  <a-select-option v-for='item in service_list' :value='item.service_id'>
                    {{ item.service_name }}
                  </a-select-option>
                </a-select>
              </td>
              <td style='min-width: 80px'><span style='color: red'>￥</span>{{ item.standard_price || '-' }}</td>
              <td>
                <span style='color: red'>￥</span>
                <a-input-number
                  :min='0'
                  style='width: 100px'
                  v-model='item.deal_price'
                  @change='(e)=>{
                    item.collection_price=e
                    item.balance_price=e-item.collection_price
                  }'
                />
                元
              </td>
              <td>
                <a-input-number :min='0' style='width: 100px' v-model='item.month' />
                月
              </td>
              <td>
                <span style='color: red'>￥</span>
                <a-input-number
                  :min='0'
                  style='width: 100px'
                  v-model='item.collection_price'
                  @change='(e)=>{
                    if(e>item.deal_price){
                      item.collection_price=item.deal_price
                    }
                    item.balance_price=item.deal_price-item.collection_price
                  }' />
                元
              </td>
              <td>
                <span style='color: red'>￥</span>{{ item.balance_price === '' ? '-' : item.balance_price }} 元
              </td>
              <td>
                <a style='color: red' @click='delFwnrList(index)'>删除</a>
              </td>
            </tr>
          </table>
        </div>
        <a-form-item label='服务说明' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-textarea
            :maxLength='500'
            v-decorator="['service_desc', { rules: [{ required: true,message: '请输入服务说明' }] }]"
            placeholder='请输入服务说明'
            :auto-size='{ minRows: 5, maxRows: 8 }'
          />
        </a-form-item>
        <a-form-item label='付款方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-radio-group
            button-style='solid'
            v-decorator="['pay_type', {initialValue:1, rules: [{ required: true }]}]"
          >
            <a-radio-button :value='1'>
              转账汇款
            </a-radio-button>
            <a-radio-button :value='2'>
              现金
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as Api from '@/api/customer/package'
import { SelectImage, Ueditor } from '@/components'
import * as serviceApi from '@/api/service'

export default {
  components: {
    SelectImage,
    Ueditor
  },
  props: {
    corporateType: {
      type: Number,
      default: 0
    },
    customerId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      mode: '',
      record: {},
      fwnr: [{
        service_id: '',
        standard_price: '',
        deal_price: '',
        month: '',
        collection_price: '',
        balance_price: ''
      }],
      service_list: []
    }
  },
  methods: {
    // 多选框搜索配置
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 显示对话框
    add() {
      this.mode = 'add'
      this.title = '增加服务'
      this.visible = true
      this.getAllService()
    },
    edit(record) {
      this.mode = 'edit'
      this.title = '编辑服务'
      this.visible = true
      this.record = record
      this.getAllService()
      this.setFieldsValue()
    },
    // 设置默认值
    setFieldsValue() {
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        this.fwnr = this.record.package_service
        const data = _.pick(this.record, Object.keys(this.record))
        setFieldsValue(data)
      })
    },
    setTrData(e, index) {
      const corporateType = this.corporateType
      const corporateTypes = [
        'gth',
        'xgmnsr',
        'ybnsr'
      ]
      const item = this.service_list.find(item => item.service_id === e)
      this.fwnr[index].standard_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].deal_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].collection_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].balance_price = 0
    },
    hasEmptyValue(arr) {
      return arr.some(obj => Object.values(obj).some(value => value === ''))
    },
    // 获取所有服务内容
    async getAllService() {
      const { data: { list } } = await serviceApi.all()
      this.service_list = list
    },
    // 增加一项服务内容
    addFwnrList() {
      this.fwnr.push({
        service_id: '',
        standard_price: '',
        deal_price: '',
        month: '',
        collection_price: '',
        balance_price: ''
      })
    },
    delFwnrList(index) {
      this.fwnr.splice(index, 1)
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    // 关闭对话框事件
    handleCancel() {
      this.visible = false
      this.form.resetFields()
      this.fwnr = [{
        service_id: '',
        standard_price: '',
        deal_price: '',
        month: '',
        collection_price: '',
        balance_price: ''
      }]
    },

    // 提交到后端api
    onFormSubmit(values) {
      var api
      if (this.mode === 'add') {
        if (this.hasEmptyValue(this.fwnr)) {
          this.$message.error('请完善服务内容！')
          return false
        }
        values.serviceTable = this.fwnr
        values.customer_id = this.customerId
        api = Api.add({ form: values })
      } else {
        api = Api.edit({ apiId: this.record['package_id'], form: values })
      }

      console.log(values)
      // return
      this.confirmLoading = true

      api.then(result => {
        // 显示成功
        this.$message.success(result.message, 1.5)
        // 关闭对话框
        this.handleCancel()
        // 通知父端组件提交完成了
        this.$emit('handleSubmit', values)
      })
        .finally(result => {
          this.confirmLoading = false
        })
    }


  }
}
</script>
